<template>
	<view>
		<watermark></watermark>
	    <page-meta :page-style="'overflow:'+(forbid_scroll?'hidden':'visible')"></page-meta>
		<uni-popup ref="popup" type="center">
			<view class="popsendCard" :style="'height:' + windowHeight + 'px'"><sendCard @click="sendCardclick"></sendCard></view>
		</uni-popup>
		<!-- 收藏 -->
		<uni-popup ref="popupfavorites" type="center" background-color="#fff" style="background-color: #fff;">
			<scroll-view scroll-y :style="'height:' + windowHeight + 'px'"><favorites type="2" @clickitem="clickitem"></favorites></scroll-view>
		</uni-popup>
		<!-- 进群申请 -->
		<view class="top_addgroup_view" v-if="weidu_addgroup_count > 0" @click="goGroupApply()">
			<image class="top_addgroup_view_img" src="/static/img/add.png"></image>
			<text class="top_addgroup_view_text">新邀请进群申请（{{weidu_addgroup_count}}）</text>
			<image class="top_addgroup_viewright_img" src="/static/img/right.png"></image>
			<view style="clear: both;"></view>
		</view>
		<view v-if="weidu_addgroup_count > 0" style="height: 80rpx;"></view>
		<!-- 消息列表 -->
		<view @click="hideTanchuang()" :class="'zfb-tk-main ' + (showtool=='' ? 'listBoxPaddingbtn ' : '') + (showEmojitool ? 'listBoxPaddingEmo ' : '')">
			<uni-list class="zfb-tk-conent" :border="false">
            <chatItem v-for="(v, index) in chatWindowData" :play_mic_id="play_mic_id" @MicId="MicId" :key="'key' + index" :id="`msg-${v.create_time}`" :talkTo="talkTo" :itemKey="index" :item="v" :pre_time="(index>0?chatWindowData[(index-1)].time:'')" @tryagin="tryagin" @longpressItem="longpressItem" :longTapItemKey="longTapItemKey" @lookimg="lookimg"></chatItem></uni-list>
			<view class="autodownView"></view>
		</view>
		<view v-if="!chatCheckedShow && show_btnmsg" class="zfb-tk-send-tool">
			<view style="line-height: 110rpx;text-align: center;font-size: 28rpx;color: #999;">{{btnmsg}}</view>
		</view>
		<view v-if="!chatCheckedShow && is_show_btn" class="zfb-tk-send-tool">
			<view class="zfb-tk-send-tool-c">
				<!-- #ifndef H5 -->
					<view class="zfb-tk-send-tool-icon wxfont" @click="changeShowVice" :class="showVice ? 'jianpan' : 'yuyin2'"></view>
				<!-- #endif -->
				<block v-if="is_jinyan">
					<view class="zfb-tk-send-tool-vioce"><view class="zfb-tk-send-tool-vioce-item" style="background: #ddd;">群成员禁言中</view></view>
				</block>
				<block v-else>
					<view class="zfb-tk-send-tool-input-box" style="text-align: center;padding-top: 0;" v-if="showVice">
						<uni-im-sound class="uni-im-sound" :maximum="maximum" @success="sendSound" @change_scroll="change_scroll"></uni-im-sound>
                    </view>
					<view v-else class="zfb-tk-send-tool-input-box" @click="msgFocus = true">
						<textarea @input="textareaInput" @focus="inpuOnfocus" :focus="msgFocus" class="zfb-tk-send-tool-input" v-model="msg" placeholder="" :cursor-spacing="12" hold-keyboard :maxlength="-1" auto-height></textarea>
					</view>
				</block>
				<view v-if="is_emoji" @click="changeEmojiTool" class="zfb-tk-send-tool-more wxfont biaoqing"></view>
				<view v-if="msg !== ''" class="zfb-tk-send-tool-text" @click="sendMsg(msg, 'TEXT')" :style="{ background: msg !== '' ? '#1BC418' : '#F7F7F7', color: msg !== '' ? '#fff' : '#ddd', 'border-color': msg !== '' ? '#1BC418' : '#ddd' }">发送</view>
				<view v-else @click="changeTool" class="zfb-tk-send-tool-more wxfont gengduo"></view>
			</view>
			<view :style="showtool" class="zfb-tk-send-tools">
				<view class="zfb-tk-send-tools-item" v-for="(v, i) in toolist" :key="i" @click="toolClick(v)" v-if="is_emoji || (!is_emoji && v.title!='文件')">
                    <block v-if="v.title!='文件'">
						<view class="zfb-tk-send-tools-icon"><view class="wxfont" :class="v.icon"></view></view>
						<view class="zfb-tk-send-tools-text">{{ v.title }}</view>
                    </block>
                    <block v-else>
						<lsj-upload
						ref="lsjUpload"
						childId="upload1"
						:width="width"
						:height="height"
						:option="option"
						:size="size"
						:formats="formats"
						:debug="debug"
						:instantly="instantly"
						@progress="onProgress"
						@uploadEnd="onuploadEnd"
						@change="onChange">
							<view class="zfb-tk-send-tools-icon"><view class="wxfont" :class="v.icon"></view></view>
						<!-- #ifdef H5 -->
							<view class="zfb-tk-send-tools-text">{{ v.title }}</view>
						<!-- #endif -->
						<!-- #ifndef H5 -->
							<view class="zfb-tk-send-tools-text">{{ v.title }}</view>
						<!-- #endif -->
						</lsj-upload>
                    </block>
				</view>
			</view>
			<scroll-view :scroll-y="true" v-if="showEmojitool && is_emoji" class="wxemojitool">
				<view class="wxemojitool-content">
					<view class="wxemojitool-item" @click="addMsg(v)" v-for="(v, i) in emojilist" :key="i">{{ v }}</view>
				</view>
			</scroll-view>
		</view>
		<zmm-upload-image chooseType="chooseMedia" :show="false" :sourceType="['album']" ref="upload" @allComplete="upLoadallComplete" @oneComplete="upLoadoneComplete" :fileList="fileList"></zmm-upload-image>
	</view>
</template>
<script>
// #ifdef APP-PLUS
//const TUICalling = uni.requireNativePlugin('TUICallingUniPlugin-TUICallingModule');
// #endif
let observer = null;
let oldScrollTop;
let is_ScrollTo =0;
import { requestUrl,micsendMsg } from '@/common/config.js';
import favorites from '../favorites/index.vue';
import chatItem from './chat-item.vue';
import sendCard from './sendCard.vue';
import emoji from "@/common/emoji.js";// 以下路径需根据项目实际情况填写
import MsgManager from '@/uni_modules/uni-im/common/msgManager.js';
import permit_app from "@/common/permit_app.js";
var app = getApp();
export default {
	components: {
		chatItem,
		sendCard,
		favorites
	},
	data() {
		return {
		    wintitle:'',groupdetail:{},
		    is_show:0,  
            // 上传接口参数
			option: {
                url: requestUrl+'/file/uploadAttach',// 上传服务器地址，此地址需要替换为你的接口地址
                name: 'file',// 上传附件的key
                header: {},// 根据你接口需求自定义请求头
                formData: {}    // 根据你接口需求自定义body参数            
            },			
			instantly: true,// 选择文件后是否立即自动上传，true=选择后立即上传
			width: '120rpx',height: '150rpx',// 必传宽高且宽高应与slot宽高保持一致
			formats: app.globalData.appconfig?app.globalData.appconfig.upload_attach_ext:'doc,wps,docx,xls,xlsx,pdf,zip,rar,mp3,apk,jpg,png,gif,jpeg,mp4,txt,amr',// 限制允许上传的格式，空串=不限制，默认为空
			size: app.globalData.appconfig?app.globalData.appconfig.upload_attach_size:10,// 附件大小上限(M)
			files: new Map(),// 文件回显列表
			wxFiles: [],// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
			debug: false,// 是否打印日志
            maximum:app.globalData.appconfig?app.globalData.appconfig.im_maximum:60,
          
			//是否为pc宽屏（width>960px）
			isWidescreen: false,
            loadMoreIng:true,
            hasMore:true,
			systemInfo: {},
            is_emoji:false,//是否显示emoji按钮
			clickToSubmitSure: null,
            forbid_scroll:0,//禁止滚动
          
			//当前会话对象id
            is_load_before:0,//加载最新数据库数据
			isBottomHeight: '',
			autodown: true,
			emojilist: emoji,
			showRecorder: false,
			showVice: false,
			toolist: [
				{
					title: '相册',
					icon: 'tupian'
				},
				{
					title: '拍摄',
					icon: 'xiangji'
				},
				{
					title: '位置',
					icon: 'dingwei'
				},{
					title: '文件',
					icon: 'wenjian'
				},
				{
					title: '收藏',
					icon: 'shoucang'
				},
				// {
				// 	title: '语音',
				// 	icon: 'yrecord'
				// },
				// {
				// 	title: '名片',
				// 	icon: 'mingpian'
				// },
			],
			msgFocus: false,
			showtool: 'display: none',
			showEmojitool: false,
			msg: '',oldmsg:'',cursorIndex:0,//光标的位置
			timer: '',
			talkTo: '',
			keyboardHeight: 0,
			windowHeight: 0,
			longTapItemKey: '',
            play_mic_id:'0',
            at_ids:'',
            at_names:'',
			// chatWindowData:[],
			localData: {},
			showtitleNViewBtns: true,
			is_jinyan: false,
			weidu_addgroup_count: 0,
			is_show_btn: true,
			collectShowUser: [],
			show_btnmsg: false,
			btnmsg: '',
			fileList: []
		};
	},
	computed: {
		userinfo() {
			return this.$store.state.userInfo;
		},
		chatListInfo() {
            var key  = this.talkTo.windowType=="GROUP"?"GROUP"+this.talkTo.userId:this.talkTo.userId;
			return this.$store.state.chatlist[key];
		},
		chatDataState() {
            var key  = this.talkTo.windowType=="GROUP"?"GROUP"+this.talkTo.userId:this.talkTo.userId;
		    var newinfo = this.$store.state.chatlist[key];
            var userinfo = this.$store.state.userInfo;
            if(newinfo && newinfo.nickName && newinfo.nickName!=this.wintitle){
                this.wintitle=newinfo.nickName;
                uni.setNavigationBarTitle({
						title: newinfo.nickName
				});
				this.collectShowUser = newinfo;
            }
            if(this.talkTo.windowType=="GROUP" && newinfo && newinfo.content){
                var ccontent = '**'+newinfo.content;//console.log(ccontent,userinfo.nickName);
                if(ccontent.indexOf(userinfo.nickName)>0 && (ccontent.indexOf('加入了群聊')>0 || ccontent.indexOf('移除群聊')>0)){
                    this.getGroupInfo(this.talkTo.userId);
                }
            }
			return this.$store.state.chatDataState;
		},
		chatDataUserId() {
			return this.$store.state.chatDataUserId;
		},
        conversation_id(){
            app.globalData.conversation_id = this.$fc.getConversationId(this.talkTo.userId,this.talkTo.windowType);
            return app.globalData.conversation_id;
        },
		currentConversation() {
			let conversation_id = this.conversation_id
			if (this.$store.state.chatDatalist[conversation_id]) {
                return this.$store.state.chatDatalist[conversation_id];
			}
		},
		isSafariPc() {
			return this.systemInfo.browserName == 'safari' && this.isWidescreen
		},
		msgobj() {
			let conversation_id = this.conversation_id;
			if (conversation_id) {
		        this.$store.dispatch('getchatDatalist',conversation_id);
                if(this.currentConversation){
                    var currentConversation = this.currentConversation;
                }else{
                    var currentConversation = this.$store.state.chatDatalist[conversation_id];
                    currentConversation.isInit=false;
                }
				return new MsgManager(currentConversation);
			}
			return {};
		},
		chatWindowData() {
            var conversation_id =  this.conversation_id;
			if (this.$store.state.chatDatalist[conversation_id]) {
                //console.log(this.$store.state.chatDatalist[conversation_id].list);
                var chatlist=this.$store.state.chatDatalist[conversation_id].list;//console.log(chatlist.length,this.is_load_before);
                if(chatlist && chatlist.length>0 && this.is_load_before==0){
                    this.is_load_before=1;
                    this.getAftermsg(chatlist);
                }
                return chatlist;
			}
		},
		chatCheckedShow(){
			var chatCheckedShow = this.$store.state.chatCheckedShow;
			this.setTopRightText(chatCheckedShow);
			return chatCheckedShow;
		}
	},
	watch: {
		chatDataState: {
			deep: true,
			immediate: true,
			handler(v) {
				if (this.chatDataUserId == this.talkTo.userId) {
					this.scrolltoBottom();
					if(this.clickToSubmitSure)this.clickToSubmitSure();
				}
			}
		}
	},
	onLoad(e) {
		this.talkTo = e;
        //调用load方法，因为pc宽屏时本页面是以组件形式展示。如$refs.chatView.loadconversation_id()执行
		this.load(this.conversation_id);
        this.is_emoji = this.$fc.check_emoji();
        const AUTH_TOKEN = ["Authorization","device","version"];
    	for (var i = 0; i < AUTH_TOKEN.length; i++) {
    		if (uni.getStorageSync(AUTH_TOKEN[i])) {
    			this.option.header[AUTH_TOKEN[i]] = uni.getStorageSync(AUTH_TOKEN[i]);
    		}
    	}
        this.clickToSubmitSure = this.$fc.debounce(
			e => {
                // 监听窗口滚动。500毫秒内滚动条高度值一致，即滚动结束时。触发加载更多消息前置方法
    			if (e && oldScrollTop == e.scrollTop && oldScrollTop<50) {
    				console.log('滚动结束', oldScrollTop,e.scrollTop);
                    uni.startPullDownRefresh();
    				//this.beforeLoadMore(e.scrollTop);
    			}
                
			},
			100,
			false
		);
        
		// 根据Id
		this.$store
			.dispatch('createChatObj', {
				userId: this.talkTo.userId,
				windowType: this.talkTo.windowType
			})
			.then(res => {
				this.localData = res.data;
				if (e.windowType == 'SINGLE') {
					uni.setNavigationBarTitle({
						title: this.localData.fromInfo.nickName
					});
				}
				this.$store.dispatch('getchatDatalist');
				this.$store.dispatch('getChatList');
				if (this.localData.fromInfo && this.localData.fromInfo.userType == 'normal') {
					// this.toolist.push({
					// 	title: '音视频',
					// 	icon: 'yspin'
					// });
				} else {
					this.$fc.setTitleNViewBtns(0, '');
					this.showtitleNViewBtns = false;
				}
				if (this.localData.groupInfo && this.localData.groupInfo.userId) {
					this.$fc.setTitleNViewBtns(0, '\ue623');
					this.showtitleNViewBtns = true;
				}
				this.scrolltoBottom();
			});
			uni.$on('manyMsgSendSuccess',function(data){
				this.$store.dispatch('setCheckedshowstatus',false);
			})
	},
	onPageScroll(e) {
        oldScrollTop = e.scrollTop;
		this.clickToSubmitSure(e);
        
		observer = uni.createIntersectionObserver(this);
		observer.relativeTo('.zfb-tk-main').observe('.autodownView', res => {
			var isBottomH = res.intersectionRect.top + res.intersectionRect.height;
			if (!this.isBottomHeight) {
				this.isBottomHeight = res.relativeRect.height + res.relativeRect.top - 56;
			}

			if (parseInt(isBottomH) < parseInt(this.isBottomHeight) + 40) {
				this.autodown = true;
			} else {
				this.autodown = false;
			}
		});
        
	},
    //下拉加载更多
    onPullDownRefresh: function() {
        this.beforeLoadMore(0);
    },
	onShow() {
	    if(this.is_show==0)this.is_show=1;
	    if(this.is_show==2){
	       this.scrolltoBottom(1);
	       this.is_show=1;
	    }
		if (this.chatListInfo && this.chatListInfo.nickName) {
			uni.setNavigationBarTitle({
				title: this.chatListInfo.nickName
			});
		}
		//群聊天，获取群详情
		if(this.talkTo.windowType == 'GROUP'){
			this.getGroupInfo(this.talkTo.userId);
		//个人聊天，好友信息
		}else{
			this.getFirendInfo(this.talkTo.userId);
		}
		var cache_send_msg = uni.getStorageSync('cache_send_msg');
		if(cache_send_msg){
			this.sendMsg(cache_send_msg,'TEXT');
			uni.setStorageSync('cache_send_msg','');
		}
		this.setTopRightText(this.$store.state.chatCheckedShow);
	},
	onHide: function() {
		console.log('App Hide')
        if(this.is_show==1)this.is_show=0;
		app.globalData.conversation_id='';
	},
	mounted() {
		// #ifdef APP-PLUS
		uni.onKeyboardHeightChange(res => {
			this.keyboardHeight = res.height;
		});
		// #endif
	},
	onUnload() {
		console.log('App onUnload')
		app.globalData.conversation_id='';
		if (observer) {
			observer.disconnect();
		}
		if (this.chatListInfo) {
			this.chatListInfo.num = 0;
            var key  = this.talkTo.windowType=="GROUP"?"GROUP"+this.talkTo.userId:this.talkTo.userId;
			this.$store.dispatch('updateChatListInfoById', { userId: key, data: this.chatListInfo });
		}
	},
	onBackPress(){
		if(this.chatCheckedShow){
			this.$store.dispatch('setCheckedshowstatus',false);
			return true;
		}
	},
	methods: {
		setTopRightText(chatCheckedShow){
			if(chatCheckedShow){
				this.$fc.setTitleNViewBtns(0,'转发','16px');
			}else{
				this.$fc.setTitleNViewBtns(0,'\ue623','28px');
			}
		},
			async load(conversation_id) {
				this.loadMoreIng = true
                uni.startPullDownRefresh();
			    this.systemInfo = uni.getSystemInfoSync()

				//设置当前会话id
				//设置全局的app当前正在聊天的会话id
				//加载数据
		        this.$store.dispatch('getchatDatalist',conversation_id);
                if (!this.msgobj.isInit) {
					//加载数据
					let data = await this.msgobj.getMore();
					// console.log('msgManagers',getApp().globalData.uniIm.msgManagers);
                    console.log('setMsgList1',data.length);
                    data = this.$fc.merage_data(this.chatWindowData,data);
					this.$fc.setMsgList({
						conversation_id: this.conversation_id,
						data
					});
				    this.scrolltoBottom(1);
					this.hasMore = !!data.length;
		            this.$store.dispatch('updateConversation',[this.conversation_id, {
						isInit: true
					}]);
                    setTimeout(()=>{
					    this.loadMoreIng = false;
                        uni.stopPullDownRefresh();
                        this.scrolltoBottom();
                    },1000);
				}
			},
            async getAftermsg(msglist){//获取线上最新的数据
                if(!msglist)msglist=this.chatWindowData;
                console.log('getAftermsg',msglist.length);
				let data = await this.msgobj.getAftermsg(msglist);
                console.log('setMsgList3',data.length);
                if(data.length>0){
                    var olddata = this.chatWindowData?this.chatWindowData:msglist;
                    data = this.$fc.merage_data(olddata,data);
					this.$fc.setMsgList({
						conversation_id: this.conversation_id,
						data
					});
				    this.scrolltoBottom(1);
                    setTimeout(()=>{
                        this.getAftermsg(data);
                    },1000);
                }
            },
			async beforeLoadMore(scrollTop) {
				if (this.isSafariPc) {
					return console.log('isSafariPc');
				}
				if (scrollTop !== false) oldScrollTop = scrollTop;
                //console.log(this.conversation_id,oldScrollTop,this.loadMoreIng,this.hasMore);
				//滚动条高度小于500且并不是正在加载中 且还有更多数据 就执行加载更多
				if (this.conversation_id && oldScrollTop < 100 && !this.loadMoreIng && this.hasMore) {
					this.loadMoreIng = true;
					return await this.loadMore(oldScrollTop);
				} else {
                    uni.stopPullDownRefresh();
					this.loadMoreIng = false;
				}
			},
			async loadMore(oldScrollTop) {
				let data = await this.msgobj.getMore();
				 console.log('加载到' + data.length + '条新数据');
				if (data.length) {
					// #ifndef APP-NVUE
                    let selector = '';
                    var olddatalength = this.chatWindowData.length;
                    if(olddatalength>0 && olddatalength>=this.msgobj.pageLimit){
                        selector = `#msg-${this.chatWindowData[0].create_time}`;
                    }
					// #endif
                    console.log('setMsgList2',data.length);
					this.$fc.setMsgList({
						conversation_id: this.conversation_id,
						action: 'unshift',
						data
					});
					uni.hideLoading();
					this.loadMoreIng = false;
				    this.scrolltoBottom();
				    this.$nextTick(() => {
				        uni.stopPullDownRefresh();
                        if(selector)this.setPageScrollTo(selector);
                    });
				} else {
					this.hasMore = false;
                    uni.stopPullDownRefresh();
					uni.hideLoading();
					this.loadMoreIng = false;
				}
				return data;
			},
       
       inpuOnfocus(){
            this.scrolltoBottom(1);
       },
		// 隐藏加载提示
		hideLoadTips(flag) {
			if (flag) {
				this.ajax.loadText = '消息获取成功';
				setTimeout(() => {
					this.ajax.loading = false;
				}, 300);
			} else {
				this.ajax.loading = true;
				this.ajax.loadText = '正在获取消息';
			}
		},
		// 设置页面滚动位置
		setPageScrollTo(selector) {
		  if(is_ScrollTo==1)return;is_ScrollTo=1;
            setTimeout(()=>{
                is_ScrollTo=0;
            },1000);
			let view = uni.createSelectorQuery().in(this).select(selector);
			view.boundingClientRect((res) => {
			    is_ScrollTo=0;
				uni.pageScrollTo({
					scrollTop: res.top, // -30 为多显示出大半个消息的高度，示意上面还有信息。
					duration: 10
				});
			}).exec();
		},
		//点击表情
		addMsg(e) {
			this.msg += e;
		},
		clickitem(e, type) {
			//发送收藏
			this.sendMsg(e.content, e.collectType);
			if(type == 1){
				this.closepopup('popupfavorites');
			}
		},
		longpressItem(e, i) {
			this.longTapItemKey = i;
		},
        change_scroll(e){//切换滚动状态
            //console.log('change_scroll',e);
            this.forbid_scroll = e;
        },//发送语音消息
        sendSound(e){console.log(e);
            if(e.recordTime > 0){
				//uni.showLoading({ title: '发送中' });
				this.$http.uploadFile({
					url: '/file/uploadAudio',
					filePath: e.recordFilePath,
					name: 'file',
					fileType: 'audio',
					success: res => {
						var data = JSON.parse(res.data);
						if (data.code == 200) {
							var msg = {
								time: e.recordTime,
								url: data.data.url,
								//text: data.data.sourceText
								text: ''
							};console.log(msg);
						    if(micsendMsg)this.playMic(micsendMsg);
							this.sendMsg(JSON.stringify(msg), 'VOICE');
						}
					}
				});
			}else{
				uni.showToast({
					title: '语音时间过短',
                    duration:2000,
                    mask:true,
					icon: 'none'
				});
                return true;
			}
            
        },
        //点击语音消息播放语音
		playMic(src) {//console.log('playMic',src);
		    var innerAudioContext ='';
		    innerAudioContext = uni.createInnerAudioContext();
		    innerAudioContext.src = src;
            innerAudioContext.autoplay = true;
            this.play_mic_id=src
            //innerAudioContext.play();
		},
		hideTanchuang() {
			this.showEmojitool = false;
			this.showtool = 'display: none';
			uni.hideKeyboard();
		},
		async changeShowVice() {
			if(this.is_jinyan){
				return false;
			}
			this.showVice = !this.showVice;
			if(this.showVice){
				this.msg = '';
				this.showEmojitool = false;
				this.showtool = 'display: none';
                await this.$fc.appCheckAuth('麦克风','android.permission.RECORD_AUDIO','record');
			}
		},
		upLoadoneComplete(e) {
			this.sendMsg(JSON.stringify(e), e.type);
		},
		upLoadallComplete(e) {
			// this.sendMsg(JSON.stringify(e),'IMAGE')
		},
		changeEmojiTool() {
			if(this.is_jinyan){
				return false;
			}
			this.showEmojitool = !this.showEmojitool;
			this.showtool = 'display: none';
			this.showVice = false;
			this.scrolltoBottom(1);
		},
		changeTool() {
			if(this.is_jinyan){
				return false;
			}
			this.showtool = this.showtool ? '' : 'display: none';
			this.showVice = false;
			this.showEmojitool = false;
			this.scrolltoBottom(1);
		},
		sendCardclick(e) {
			this.$refs.popup.close();
			this.sendMsg(JSON.stringify(e.item.data), 'CARD');
		},
		open() {
			uni.getSystemInfo({
				success: res => {
					this.windowHeight = res.windowHeight;
				}
			});
			this.$refs.popup.open('top');
		},
		closepopup(e) {
			this.$refs[e].close();
		},
		openpopup(e) {
			this.$refs[e].open('top');
		},
        MicId(e){
            this.play_mic_id=e;
        },
		lookimg(url){
		    this.hideTanchuang();
			var list = this.chatWindowData;
			var imgObj = [];
			var imgkey = 0;
			var current = 0;
			for(var i = 0; i < list.length; i++){
				if(list[i]['msgType'] == 'IMAGE'){
					var list_imgurl = this.returnParse(list[i]['content']).url;
					imgObj.push(list_imgurl);
					if(list_imgurl == url){
						current = imgkey;
					}
					imgkey++;
				}
			}
            if(this.msgFocus){
                setTimeout(()=>{
                    this.$fc.previewImages(imgObj,current);
                },100);
            }else{
                this.$fc.previewImages(imgObj,current);
            }
		},
		returnParse(txt) {
			if(typeof txt == 'object'){
				return txt;
			}else{
				return JSON.parse(txt);
			}
		},
		tryagin(e, i) {
			//重新发送
            var conversation_id = this.$fc.getConversationId(this.talkTo.userId,this.talkTo.windowType);
			this.chatWindowData.splice(i, 1);
			this.chatWindowData.splice(i, 1);
			this.$store.dispatch('updateChatById', {
				conversation_id: conversation_id,
				data: this.chatWindowData
			});
			this.$nextTick(() => {
				this.sendMsg(e.content, e.msgType);
			});
		},
		sendVoiceCall() {
			//发起语音
			uni.showLoading({
				title: '发起语音通话'
			});
			var formdata = {
				userId: this.talkTo.userId,
				msgType: 'TRTC_VOICE_START',
				content: 'TRTC_VOICE_START'
			};
			this.$http.request({
				url: '/chat/sendMsg',
				method: 'POST',
				data: JSON.stringify(formdata),
				success: res => {
					if (res.data.code == '200') {
						if (res.data.data.status !== '0') {
							uni.showToast({
								title: res.data.data.statusLabel,
								icon: 'none'
							});
							return;
						}
						var userInfo = res.data.data.userInfo;
						var data = {
							userId: userInfo.userId,
							trtcId: userInfo.trtcId,
							nickName: userInfo.nickName,
							portrait: userInfo.portrait,
							startTime: new Date().getTime(),
							type: 'audio'
						};
						uni.setStorage({
							key: 'call',
							data: JSON.stringify(data),
							success: function() {
								TUICalling.call({
									userID: userInfo.trtcId,
									type: 1
								});
							}
						});
					}
				}
			});
		},
		sendVideoCall() {
			//发起视频
			uni.showLoading({
				title: '发起视频通话'
			});
			var formdata = {
				userId: this.talkTo.userId,
				msgType: 'TRTC_VIDEO_START',
				content: 'TRTC_VIDEO_START'
			};
			this.$http.request({
				url: '/chat/sendMsg',
				method: 'POST',
				data: JSON.stringify(formdata),
				success: res => {
					if (res.data.code == '200') {
						if (res.data.data.status !== '0') {
							uni.showToast({
								title: res.data.data.statusLabel,
								icon: 'none'
							});
							return;
						}
						var userInfo = res.data.data.userInfo;
						var data = {
							userId: userInfo.userId,
							trtcId: userInfo.trtcId,
							nickName: userInfo.nickName,
							portrait: userInfo.portrait,
							startTime: new Date().getTime(),
							type: 'video'
						};
						uni.setStorage({
							key: 'call',
							data: JSON.stringify(data),
							success: function() {
								TUICalling.call({
									userID: userInfo.trtcId,
									type: 2
								});
							}
						});
					}
				}
			});
		},
		async toolClick(e) {
			switch (e.title) {
				case '位置':
					//地理位置权限验证
					var auth_status = await this.$fc.appCheckAuth('地理位置','android.permission.ACCESS_FINE_LOCATION','location');
					if(auth_status == 1){
						uni.chooseLocation({
							success: res => {
								this.sendMsg(JSON.stringify(res), 'LOCATION');
							}
						});
					}
					break;
				case '相册':
					//相册权限验证
					var auth_status = await this.$fc.appCheckAuth('相册','android.permission.READ_EXTERNAL_STORAGE','photoLibrary');
					if(auth_status == 1){
						this.fileList = [];
						this.$refs['upload'].chooseTap();
					}
					break;
				case '语音':
					//录音权限验证
					var auth_status = await this.$fc.appCheckAuth('麦克风','android.permission.RECORD_AUDIO','record');
					if(auth_status == 1){
						this.startRecord();
					}
					break;
				case '名片':
					this.open();
					break;
				case '音视频':
					uni.showActionSheet({
						itemList: ['视频通话', '语音通话'],
						success: res => {
							switch (res.tapIndex) {
								case 0:
									this.sendVideoCall();
									break;
								case 1:
									this.sendVoiceCall();
									break;
								default:
									break;
							}
						}
					});
					break;
				case '收藏':
					uni.navigateTo({
						url: this.$fc.get_package_name()+'favorites/index?type=2&collectShowUser=' + JSON.stringify(this.collectShowUser)
					})
					break;
				case '拍摄':
					var _this = this;
					//摄像头权限验证
					var auth_status = await this.$fc.appCheckAuth('摄像头','android.permission.CAMERA','camera');
					if(auth_status == 1){
						uni.showActionSheet({
							itemList: ['图片', '视频'],
							success: res => {
								switch (res.tapIndex) {
									case 0:
										getImage();
										break;
									case 1:
										getVideo();
										break;
									default:
										break;
								}
							},
							fail: function(res) {
								console.log(res.errMsg);
							}
						});
						function getImage() {
							uni.chooseImage({
								count: 1,
								sizeType: ['original', 'compressed'],
								sourceType: ['camera'],
								success: function (res) {
									sendPhoto(res.tempFilePaths[0]);
								}
							});
						}
						function getVideo() {
							uni.chooseVideo({
								sourceType: ['camera'],
								compressed: true,
								success: function (res) {
									sendVideo(res.tempFilePath);
								}
							});
						}						
						function sendPhoto(filePath) {
							uni.showLoading({
								title: '上传中...'
							})
							//发送图片
							_this.$http.uploadFile({
								url: '/file/upload',
								filePath: filePath,
								name: 'file',
								fileType: 'image',
								success: res => {
									uni.hideLoading();
									var data = JSON.parse(res.data);
									if (data.code == 200) {
										var msg = {
											name: data.data.name,
											url: data.data.url
										};
										_this.sendMsg(JSON.stringify(msg), 'IMAGE');
									}
								}
							});
						}
						function sendVideo(filePath) {
							uni.showLoading({
								title: '上传中...'
							})
							//发送视频
							_this.$http.uploadFile({
								url: '/file/uploadVideo',
								filePath: filePath,
								name: 'file',
								fileType: 'video',
								success: res => {
									uni.hideLoading();
									var data = JSON.parse(res.data);
									if (data.code == 200) {
										var msg = {
											name: data.data.name,
											videoUrl: data.data.url,
											url: data.data.screenShot
										};
										_this.sendMsg(JSON.stringify(msg), 'VIDEO');
									}
								}
							});
						}
					}
					break;
				default:
					break;
			}
		},
		sendMsg(e, msgType) {
            this.hideTanchuang();
			if (!e) {
				return;
			}
			if(this.is_jinyan){
				uni.showToast({
					title: '群成员禁言中',
					icon: 'none'
				})
				return false;
			}
            var msgContent = e;
            if(msgType=='TEXT' && this.at_ids){
                msgType='TEXTAT';
                var atContent={};
                atContent.content = e;
                atContent.ids = this.at_ids;
                atContent.names = this.at_names;
                msgContent =  JSON.stringify(atContent);
            }
			this.$fc.pushOutMsg({
				msgContent:msgContent,
				msgType: msgType,
				windowType: this.talkTo.windowType,
				userId: this.talkTo.userId
			});
			this.msg = '';
            this.at_ids = '';
            this.at_names = '';
			// #ifdef H5
			this.msgFocus = false;
			this.$nextTick(() => {
				this.msgFocus = true;
			});
			// #endif
		},
		startRecognize() {
			//语音文本输入
			// #ifdef H5
			uni.showToast({
				title: 'H5暂不支持',
				icon: 'none'
			});
			return;
			// #endif
			let _this = this;
			let options = {};
			options.engine = 'baidu';
			options.punctuation = false; // 是否需要标点符号
			options.timeout = 10 * 1000;
			plus.speech.startRecognize(
				options,
				function(s) {
					_this.msg = _this.msg + s;
				},
				function(e) {
					uni.showToast({
						title: '语音识别失败：' + e.message,
						icon: 'none'
					});
				}
			);
		},
		scrolltoBottom(is_real) {//console.log('scrolltoBottom',this.autodown,is_real)
			if (this.autodown || is_real==1) {
				this.$nextTick(() => {
					this.timer = setTimeout(() => {
					    if(this.is_show==0)this.is_show=2;
						uni.pageScrollTo({
							scrollTop: 9999999,
							duration: 10
						});
					}, 200);
				});
			}
		},
        onuploadEnd(value) {//结束
                var self = this;
                if (value['responseText']) {
                    var responseText = JSON.parse(value.responseText);
                    if(responseText.code==200){//上传成功
                        var message = responseText.data;
                        var name = value.name;
        				var type =message.ext?message.ext: this.$fc.getType(value.name);
        				var size = value.size;
                        var fresult={};var ftype='';
                        if(type=='jpg' || type=='jpeg' || type=='png' || type=='gif'){
                            fresult={
									name: name,
									url: message.url,
									type:'IMAGE'
								};
                            ftype = 'IMAGE';
                        }else if(type=='mp4'){
                            fresult={
                                    name: name,
									videoUrl: message.url,
									url: message.screenShot,
									type:'VIDEO'
							};
                            ftype = 'VIDEO';
                        }else{
                            fresult={
									name: name,
                                    size: size,ext:type,
									url: message.url,
									type:'FILE'
							};
                            ftype = 'FILE';
                        }
                        //console.log('sendMsg',fresult);
                        var msgContent = JSON.stringify(fresult);
                        this.$fc.pushSendingMsg(msgContent,ftype,
            				 this.talkTo.windowType,
            				 this.talkTo.userId,name,'success'
            			);
                    }else{
                        var errormsg = responseText.msg?responseText.msg:'上传失败';
                        uni.showToast({title: errormsg,icon: 'none'});return;
                    }
                }
            },
            onProgress(value) {//console.log('onProgress',value);//进度
                if(value.progress==0)return '';
                if(value.progress==100)value.progress=99;
                var name = value.name;
				var type = this.$fc.getType(value.name);
				var size = value.size;
                var ftype = 'FILE';
                
                var fresult={
        				progress_show:1,
        				progress_num:value.progress,
        				progress_color:'#409eff',
						name: name,
                        size: size,ext:type,
						url: value.path,
						type:ftype
				};
                var othermsg = {
        				progress_show:1,
        				progress_num:value.progress,
        				progress_color:'#409eff',
				};
                //console.log('sendMsg',fresult);
                var msgContent = JSON.stringify(fresult);
                this.$fc.pushSendingMsg(msgContent,ftype,this.talkTo.windowType,
    				this.talkTo.userId,name,'progress',othermsg);
            },
            onChange(files) {// 文件选择回调
                //console.log('onChange',files);
                var self = this;
            },
			//群详情
			getGroupInfo(groupid){
				this.$http.request({
					url: '/group/getInfo/?id=' + groupid + '&is_not_user=1',
					success: res => {
						if (res.data.code == 200) {
							var groupdetail = res.data.data;
                            this.groupdetail = groupdetail;
							if(groupdetail.is_forbid == 1 && groupdetail.user_type == 'member'){
								this.is_jinyan = true;
							}else{
								this.is_jinyan = false;
							}
                            if(groupdetail.name!=this.wintitle){
                                this.wintitle=groupdetail.name;
                                uni.setNavigationBarTitle({
                						title: groupdetail.name
                				});
                                var key = 'GROUP'+groupid;
                                var data=this.$store.state.chatlist && this.$store.state.chatlist[key]?this.$store.state.chatlist[key]:{};
							    data.nickName=groupdetail.name
    							this.$store.dispatch('updateChatListInfoById', {
    								userId: key,
    								data: data
    							});
                            }
							this.weidu_addgroup_count = groupdetail.weidu_addgroup_count;
							this.is_show_btn = true;
							uni.setNavigationBarTitle({
								title: groupdetail.name + '(' + groupdetail.sum_member + ')'
							});
						}else{
							this.is_show_btn = false;
							if(res.data.data){
								if(res.data.data.not_send == 'on'){
									this.show_btnmsg = true;
									this.btnmsg = res.data.data.msg;
								}
							}
						}
					}
				});
			},
			//好友详情
			getFirendInfo(firend_uid){
				this.$http.request({
					url: '/friend/info/?id=' + firend_uid,
					success: (res) => {
						if (res.data.code == 200) {
							var firend_detail = res.data.data;
							if(firend_detail.isFriend == 'N'){
								this.is_show_btn = false;
								this.show_btnmsg = true;
								this.btnmsg = '已删除的好友无法发送消息';
							}
						}
					}
				});
			},
			goGroupApply(){
				uni.navigateTo({
					url: '../groupInfo/applyAddGroup?groupId=' + this.talkTo.userId
				});
			},
			duoMsgZhuanfa(){
				var chat_msg_list = this.$store.state.chat_msg_list;
				var msgList = [];
				for(var i in chat_msg_list){
					if(chat_msg_list[i] != ''){
						msgList.push(chat_msg_list[i]);
					}
				}
				if(msgList.length <= 0){
					uni.showToast({
						title: '至少选择一条消息',
						icon: 'none',
						position: 'bottom'
					})
					return;
				}
				msgList.sort((a, b) => {
					return Math.round(a['create_time']/1000) - Math.round(b['create_time']/1000);
				});
				var newObj = {};
				newObj.windowType = this.talkTo.windowType;
				newObj.msgList = msgList;
				newObj.form_id = this.$store.state.userInfo.userId;
				newObj.to_id = this.talkTo.userId;
				uni.showLoading({
					title: '加载中...'
				})
				this.$http.request({
					url: '/chat/manyMsgChuli',
					method: 'POST',
					data: JSON.stringify(newObj),
					success: res => {
						if (res.data.code == 200) {
							var data = {};
							data.content = JSON.stringify(res.data.data);
							data.msgType = 'manyMsg';
							uni.navigateTo({
								url: this.$fc.get_package_name()+'message_zhuanfa/index?data=' + JSON.stringify(data)
							})
						}
					}
				});
			},
            // 用户输入@
            textareaInput(e) {
                if(this.talkTo.windowType!="GROUP")return;
                var content = e.detail.value;
                if(content==''){this.at_ids='';this.at_names='';return;}
                
                //const oldArr = this.oldmsg?this.oldmsg.split(''):'';
                const newArr = content.split('');
                // 找出当前输入的内容
                let contentStr = content;
                if(this.oldmsg){
                    contentStr= content.replace(this.oldmsg,'');
                }
                //console.log(this.oldmsg+'=='+content+'=='+contentStr);
                // 输入是@时
                if(contentStr === '@' || content=== '@'){                    
                    // 比对算法,找出当前光标的位置,找到当前输入的位置
                    newArr.some((now,index) => {
                        if(content.substr(0,index) !==  this.oldmsg.substring(0,index)){
                            this.cursorIndex = index;
                            return true;
                        }
                        this.cursorIndex = 0;
                    })
                }
                if(contentStr === '@' || content=== '@'){
					uni.navigateTo({
						url: this.$fc.get_package_name()+'groupInfo/qunAt?groupId='+this.talkTo.userId+'&user_type='+this.groupdetail.user_type
					})
                }
                this.oldmsg = content;
        },
		changeData(data) {
		    //console.log(data);
            if(!data.names)return ;
            if(data.ids=='all'){
                this.at_ids=data.ids;
                this.at_names=data.names;
            }else{
                this.at_ids=this.at_ids?this.at_ids+','+data.ids:data.ids;
                this.at_names=this.at_names?this.at_names+','+data.names:data.names;
            }
            const span= '@'+data.names+' ';
            let html = this.msg;
            // 光标位置为0在后面追加,不为0从中间替换
            if(this.cursorIndex){
                html = html.substr(0,this.cursorIndex-1)+span+html.substr(this.cursorIndex,html.length)
            }else{
                html = html.substr(0,html.length-1)+span;
            }
            this.oldmsg = html;
            this.msg = html;
            this.oldContent = this.msg
		},
		beforeDestroy() {console.log('销毁ws！')
			//销毁ws
			app.globalData.conversation_id='';
		}
	},
	onNavigationBarButtonTap(e) {
		if (!this.showtitleNViewBtns) {
			return;
		}
		switch (e.index) {
			case 0:
				if(this.chatCheckedShow){
					this.duoMsgZhuanfa();
				}else{
					if (this.talkTo.windowType == 'GROUP') {
						uni.navigateTo({
							url: '../groupInfo/detail?param=' + this.talkTo.userId
						});
					}
					if (this.talkTo.windowType == 'SINGLE') {
						uni.navigateTo({
							url: '../personInfo/detail?param=' + this.talkTo.userId + '&laiyuan=info'
						});
					}
				}
				break;
			default:
				break;
		}
	}
};
</script>
<style>
	page{
		background: #ededed;
	}
</style>
<style lang="scss" scoped>
.autodownView {
	height: 1px;
	width: 100%;
	opacity: 0;
}
.zfb-tk-conent{
		flex: 1;
		background-color: #ededed;
		/* #ifdef H5 */
		margin-top: 45px;
		/* #endif */
}
.zfb-tk-main {
	padding: 0 12px;
	padding-bottom: 120rpx;
	background-color: #ededed;
}

.zfb-tk-send-tool {
	background: #f7f7f7;
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100%;
	/*transition: all 0.1s;*/
	box-sizing: content-box;
			z-index: 2;
			height: auto;
	/* 兼容iPhoneX */
	padding-bottom: 0;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	>view {
		padding: 0 20rpx;
		min-height: 110rpx;
	}
}
.zfb-tk-send-tools {
	height: 480rpx;
	width: 100%;
	background-color: #f7f7f7;
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	align-items: center;
}
.zfb-tk-send-tools-item {
	padding: 35rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
    text-align:center;
}
.zfb-tk-send-tools-icon {
	background-color: #fff;
	width: 110rpx;
	height: 110rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: center;
	border-radius: 12rpx;
}
.zfb-tk-send-tools-icon .wxfont {
	color: #181818;
	font-size: 64rpx;
}
.zfb-tk-send-tools-text {
	font-size: 24rpx;
	color: #666;
}
.zfb-tk-send-tool-c {
	position: relative;
	z-index: 3;
	padding: 16rpx 12rpx;
	box-sizing: border-box;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-around;
	border: 1px #ddd solid;
	border-left: none;
	border-right: none;
}

.zfb-tk-send-tool-c .zfb-tk-send-tool-btn {
	transition: color 0.5s;
}
.zfb-tk-send-tool-input-box {
	overflow: auto;
	width: 100%;
	margin: 0 12rpx;
	min-height: 80rpx;
	background-color: #fff;
	border-radius: 24rpx;
	padding-top: 18rpx;
	max-height: 240rpx;
	box-sizing: border-box;
}
.zfb-tk-send-tool .zfb-tk-send-tool-input {
	padding: 0 24rpx;
	box-sizing: border-box !important;
	width: 100%;
	background: #fff;
}
.zfb-tk-send-tool-vioce {
	box-sizing: border-box;
	margin: 0 12rpx;
	width: 100%;
	height: 75rpx;
	border-radius: 24rpx;
	background: #fff;
	display: flex;
	flex-direction: row;
	align-items: center;
}
.zfb-tk-send-tool-vioce-item {
	text-align: center;
	font-size: 32rpx;
	line-height: 80rpx;
	flex: 1;
}
.zfb-tk-send-tool-vioce-item:nth-child(1) {
	border-right: 1px #eee solid;
}
.zfb-tk-send-tool-text {
	white-space: nowrap;
	padding: 10rpx 24rpx;
	border-radius: 12rpx;
	border: 1px #ddd solid;
	background: #f7f7f7;
	color: #ddd;
}
.zfb-tk-send-tool-more {
	font-size: 80rpx;
	color: #333;
}
.zfb-tk-send-tool-icon {
	font-size: 80rpx;
	color: #333;
}
.zfb-tk-recorder {
	width: 350rpx;
	height: 350rpx;
	left: 50%;
	margin-left: -175rpx;
	top: 50%;
	margin-top: -250rpx;
	box-sizing: border-box;
	text-align: center;
	position: fixed;
	// background-color: #f8f8f8;
	box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
	// padding: 20rpx;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: center;
	z-index: 99999;
	background: rgba(0, 0, 0, 0.7);
}
.popsendCard {
	display: flex;
	background-color: #fff;
	overflow: auto;
}
.popsendCard-close {
	width: 100%;
	text-align: center;
	height: 70rpx;
	line-height: 70rpx;
	font-size: 42rpx;
	background-color: #fff;
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 9999;
}
.wxemojitool {
	height: 558rpx;
}
.wxemojitool-content {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
}
.wxemojitool-item {
	font-size: 44rpx;
	width: 93rpx;
	height: 93rpx;
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
}
.top_addgroup_view{
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	position: fixed;
	/* #ifdef H5 */
		top: 44px;
	/* #endif */
	/* #ifndef H5 */
		top: 0;
	/* #endif */
	left: 0;
	background: #ffffff;
	z-index: 9;
}
.top_addgroup_view_img{
	width: 40rpx;
	height: 40rpx;
	margin: 20rpx 20rpx 20rpx 40rpx;
	float: left;
}
.top_addgroup_view_text{
	display: block;
	height: 80rpx;
	line-height: 80rpx;
	float: left;
	font-size: 28rpx;
}
.top_addgroup_viewright_img{
	width: 40rpx;
	height: 40rpx;
	margin: 20rpx;
	float: right;
}

.listBoxPaddingbtn {
	padding-bottom: 600rpx;
}
.listBoxPaddingEmo {
	padding-bottom: 678rpx;
}
</style>
